<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>springboot项目WebSocket测试demo</title>
</head>
<body>
<h3>springboot项目websocket测试demo</h3>
<h4>测试说明</h4>
<h5>文本框中数据数据，点击‘发送测试’，文本框中的数据会发送到后台websocket，后台接受到之后，会再推送数据到前端，展示在下方；点击关闭连接，可以关闭该websocket；可以跟踪代码，
了解具体的流程；代码上有详细注解</h5>
<br />
<input id="text" type="text" />
<button onclick="send()">发送测试</button>
<hr />
<button onclick="clos()">关闭连接</button>
<hr />
<div id="message"></div>
<script>
    var websocket = null;
    if('WebSocket' in window){
        websocket = new WebSocket("ws://127.0.0.1:8000/man/websocket/1");
    }else{
        alert("您的浏览器不支持websocket");
    }
	//连接发生错误的进行触发
    websocket.onerror = function(){
	    
        setMessageInHtml("send error！");
    }
	//websocket 链接成功后进行触发
    websocket.onopen = function(){
	    console.log("建立链接。。。。");
        setMessageInHtml("connection success！")
    }
	//接收到消息的进行触发
    websocket.onmessage  = function(event){
	    console.log("收到消息");
        setMessageInHtml(event.data);
    }
	//websocket 链接关闭的进行触发
    websocket.onclose = function(){
	    console.log("关闭链接。。。。");
        setMessageInHtml("closed websocket!")
    }
	
	//当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        clos();
    }
    function setMessageInHtml(message){
        document.getElementById('message').innerHTML += message;
    }
	//关闭websocket连接
    function clos(){
        websocket.close(3000,"强制关闭");
		 //websocket.close();
    }
    function send(){
        //var msg = document.getElementById('text').value;
        //websocket.send(msg);
		
		var sendIput = document.getElementById("text");
            var sendMessage = sendIput.value;
            if(sendMessage.trim() == ""){
                alert("请输入发送消息！")
                return;
            }
            websocket.send(sendMessage);
    }
</script>
</body>
</html>